//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    // 订单状态
    orderStatus: null,
    data: {},
    imgurl: app.urlimg,
    images: {},
    actionType: 'buy',
    address_id: '',
    cart_id: '',
    payIndex: 1,
    paymethod: ['真爱卡支付', '微信支付'],
    // paymethod: ['真爱卡支付', '微信支付', '货到付款'],
    payId: 1,
    isAnimation: false,
    //  活动优惠
    sale_box: [],
    //控制商品数量的“加”“减”号的显示与隐藏
    control: [],
    pTuan: 0,  //是否为拼团
    tSign: 0,//团唯一标识
    regiment_id: 0, //团唯一标识,
    couponId: 0,//优惠券id
    discount_text: '',
    sale_box_checked: [, [0], [0, 0]],
    //支付次数
    Pay_num: 3,
    //骆驼卡
    //骆驼卡支付
    camel_card_pay: false,
    //骆驼卡支付密码错误
    camel_card_error: false,
    camel_card_password: '',
    camel_pay_tips: '密码输入错误！请重新输入',
    // 支付下拉框动画
    pay_stat: 0,
    animationImg: {},
    animationText: {},
  },
  onLoad: function (e) {
    var that = this;
    if (e.pTuan && e.tSign) {
      that.setData({
        pTuan: e.pTuan,
        tSign: e.tSign,
      });
    }
    that.setData({ isOnLoad: 1 })
    // 默认支付方式 关闭窗口
    var animationImg = wx.createAnimation({}), animationText = wx.createAnimation({});
    this.animationImg = animationImg;
    this.animationText = animationText;
    animationImg.rotate(180).step();
    animationText.height(0).step();

    that.setData({
      regiment_id: (e.regiment_id ? e.regiment_id : '0'),
      group_type: (e.group_type ? e.group_type : '0'),
      animationImg: animationImg,
      animationText: animationText,
    });

    if (e.actionType == 'buy') {
      buyData(that, e.goods_id, e.product_id, e.number)
    } else if (e.actionType == 'cart') {
      carData(that, e.cart_id)
    }

  },
  // 打开 和 关闭 支付方式
  pay_state: function () {
    var that = this,
      animationImg = wx.createAnimation({
        duration: 500,
        timingFunction: 'ease',
      }),
      animationText = wx.createAnimation({
        duration: 500,
        timingFunction: 'ease',
      });
    this.animationImg = animationImg;
    this.animationText = animationText;
    var pay_stat = that.data.pay_stat;
    if (pay_stat) {
      pay_stat = 0;
      animationImg.rotate(180).step();
      animationText.height(0).step();
    } else {
      pay_stat = 1;
      animationImg.rotate(0).step();
      animationText.height(100).step();
    }

    that.setData({
      pay_stat: pay_stat,
      animationImg: animationImg,
      animationText: animationText,
    });
  },
  imageLoad: function (e) {
    var $width = e.detail.width,    //获取图片真实宽度
      $height = e.detail.height,
      ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = 718,           //设置图片显示宽度，左右留有16rpx边距
      viewHeight = 718 / ratio;    //计算的高度值
    var image = this.data.images;
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    image[e.target.dataset.index] = {
      width: viewWidth,
      height: viewHeight
    }
    this.setData({
      images: image
    })
  },
  swiperItem: function (e) {
    var that = this;
    // 页面跳转
    if (e.currentTarget.dataset.url != '') {
      wx.navigateTo({
        url: e.currentTarget.dataset.url,
      })
    }
  },
  //关闭骆驼卡支付窗口
  camel_card_off: function () {
    //this.setData({ camel_card_pay: false, camel_card_password: '', })
    wx.redirectTo({
      url: '/pages/account/order/index?fid=' + 0,
    })
  },
  // 选择支付
  select_pay: function (e) {
    var that = this
    if (e.currentTarget.dataset.index == 0) {
      if (parseFloat(that.data.data.total_price) > parseFloat(that.data.data.camel_card_balance)) {
        wx.showToast({
          title: '骆驼卡余额不足',
          icon: 'loading',
          duration: 1000,
          mask: true
        })
        return
      }
    }

    var payId = getPayId(e.currentTarget.dataset.index);//后台提交的支付id
    this.setData({ payIndex: e.currentTarget.dataset.index, payId: payId })
  },
  //骆驼卡支付密码
  camel_card_input: function (e) {
    var that = this;
    that.setData({
      camel_card_password: e.detail.value,
    })
  },
  // 骆驼卡支付
  camel_card_toPay: function (e) {
    var that = this;
    if (that.data.camel_card_password.length > 0) {
      console.log('骆驼卡支付');
      wx.request({
        url: app.url + 'api_order/camelCardPay',
        data: {
          pay_passwd: that.data.camel_card_password,
          order_id: that.data.orderId,
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        }, success: function (json) {
          console.log(json)
          if (json.data.done == true) {
            wx.redirectTo({
              url: '/pages/account/order/index?fid=' + 0,
            })
          } else {
            that.setData({
              camel_card_error: true,
              camel_pay_tips: json.data.message,
            })
          }
        }
      })
    } else {
      that.setData({
        camel_card_error: true,
        camel_pay_tips: '请输入骆驼卡支付密码',
      })
    }
  },
  // 确认支付
  toPay: function (e) {
    var that = this;
    var Pay_num = that.data.Pay_num;
    if (Pay_num > 0) {
      Pay_num--;
      that.setData({
        Pay_num: Pay_num,
      })
      var regiment_userid = wx.getStorageSync('regiment_userid');
      var regiment_share_userid = wx.getStorageSync('regiment_share_userid');
      var couponId = that.data.couponId;
      var group_type = that.data.group_type;
      if (group_type == 4) {
        this.setData({
          payId: 2,
        });
      }
      if (that.data.payIndex == 0) {
        console.log('骆驼卡支付');
        //that.setData({ camel_card_pay:true,})
        buy_goods();
      } else if (that.data.payIndex == 1) {
        console.log('微信支付');
        buy_goods();
      } else if (that.data.payIndex == 2) {
        console.log('货到付款');
        wx.showModal({
          title: '确认使用货到付款吗？',
          content: '货到付款订单总价：￥' + that.data.data.total_price + '\r\n客服会电话回访确认，请保持电话畅通',
          success: function (res) {
            if (res.confirm) {
              buy_goods();
            }
          }
        })
      }
      function buy_goods() {
        if (that.data.actionType == 'buy') {
          wx.request({
            url: app.url + 'api_order/doneOrder',
            data: {
              goods_id: that.data.data.goods[0].goods_id,
              product_id: that.data.data.goods[0].product_id,
              number: that.data.data.goods[0].number,
              address_id: that.data.data.address.id,
              postscript: e.detail.value.postscript,
              pay_type: that.data.payId,
              regiment_userid: (regiment_userid != undefined) ? regiment_userid : 0,
              regiment_share_userid: (regiment_share_userid != undefined) ? regiment_share_userid : 0,
              regimentid: (that.data.data.goods[0].regimentid != undefined) ? that.data.data.goods[0].regimentid : 0,
              form_id: e.detail.formId,
              pintuan: (that.data.pTuan != 0) ? that.data.pTuan : wx.getStorageSync('pintuan'),
              teamSign: (that.data.tSign != 0) ? that.data.tSign : 0,
              regiment_id: (that.data.regiment_id != undefined) ? that.data.regiment_id : 0,
              couponId: (that.data.couponId != undefined) ? that.data.couponId : 0,
              repeatId: (!that.data.repeatId || that.data.repeatId == 'undefined' ? '0' : that.data.repeatId),
            },
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token_key')
            }, success: function (json) {
              if (json.data.result == '参团人数已满') {
                wx.showModal({
                  title: '提示',
                  content: '抱歉，' + json.data.result,
                })
              } else {
                if (parseInt(json.data.result.payType) == 2) {
                  that.getTeamStatus(json.data.result.orderId);
                  return;
                }

                if (json.data.done) {
                  if (that.data.payIndex == 1) {
                    wx.requestPayment({
                      'appId': json.data.result.appid,
                      'timeStamp': json.data.result.timeStamp.toString(),
                      'nonceStr': json.data.result.nonceStr,
                      'package': json.data.result.package,
                      'signType': 'MD5',
                      'paySign': json.data.result.sign,
                      'success': function (res) {
                        console.log(res);
                        if (wx.getStorageSync('pintuan') == 1) {
                          that.getTeamStatus(json.data.result.orderId);
                        } else {
                          wx.redirectTo({
                            url: '/pages/account/succeed/index?orderId=' + json.data.result.orderId,
                          })
                        }
                      },
                      fail: function (res) {
                        wx.showToast({
                          title: '支付失败！',
                          image: '/pages/icon/delete.png',
                          duration: 1200,
                          mask: true,
                          complete: function () {
                            setTimeout(function () {
                              wx.redirectTo({
                                url: '/pages/account/order/index?fid=0',
                              })
                            }, 1200)
                          } //接口调用结束的回调函数  
                        })
                      },
                    })

                  } else if (that.data.payIndex == 2) {
                    //货到付款
                    wx.redirectTo({
                      url: '/pages/account/order/index?fid=' + 0,
                    })
                  }
                  else if (that.data.payIndex == 0) {
                    //真爱支付
                    that.setData({ camel_card_pay: true, orderId: json.data.result.order_id })
                  }

                } else {
                  // app.apperror(json);
                }
              }
            }
          })
        } else if (that.data.actionType == 'cart') {
          wx.request({
            url: app.url + 'api_order/doneOrderV1',
            data: {
              cart_id: that.data.cart_id,
              address_id: that.data.data.address.id,
              postscript: e.detail.value.postscript,
              pay_type: that.data.payId,
              couponId: (that.data.couponId != undefined) ? that.data.couponId : 0,
              repeatId: (!that.data.repeatId || that.data.repeatId == 'undefined' ? '0' : that.data.repeatId),
            },
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token_key')
            }, success: function (json) {
              if (json.data.done) {
                if (that.data.payIndex == 1) {
                  wx.requestPayment({
                    'appId': json.data.result.appid,
                    'timeStamp': json.data.result.timeStamp.toString(),
                    'nonceStr': json.data.result.nonceStr,
                    'package': json.data.result.package,
                    'signType': 'MD5',
                    'paySign': json.data.result.sign,
                    'success': function (res) {
                      wx.redirectTo({
                        url: '/pages/account/order/index?fid=' + 0,
                      })

                    },
                    'fail': function (res) {
                      app.apperror(res);
                      wx.showModal({
                        title: '提示',
                        content: '支付失败！',
                        success: function (res) {
                          if (res.confirm) {
                            console.log('用户点击确定')
                          }
                          wx.redirectTo({
                            url: '/pages/account/order/index?fid=' + 0,
                          })
                        }

                      })
                    },
                  })

                } else if (that.data.payIndex == 2) {
                  //货到付款
                  wx.redirectTo({
                    url: '/pages/account/order/index?fid=' + 0,
                  })

                } else if (that.data.payIndex == 0) {
                  //真爱支付
                  that.setData({ camel_card_pay: true, orderId: json.data.result.order_id })
                }

              } else {
                // app.apperror(json);
              }
            }
          })
        }
      }

    } else {
      wx.showModal({
        title: '提示',
        content: '请勿重复确认支付',
        success: function (res) {
        }
      })
    }
  },
  onShow: function (e) {
    var that = this;
    if (that.data.isOnLoad == 1) {
      that.setData({ isOnLoad: 0 })
      return
    }


    wx.request({
      url: app.url + 'api_user/chooseAddress',
      data: {
        address_id: that.data.address_id
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')

      }, success: function (json) {
        if (json.data.done == true) {
          var result = json.data.result;
          var newdata = that.data.data;
          newdata.address.accept_name = result.accept_name
          newdata.address.mobile = result.mobile
          newdata.address.province_name = result.province_val
          newdata.address.city_name = result.city_val
          newdata.address.area_name = result.area_val
          newdata.address.address = result.address
          newdata.address.id = result.id;

          var payIndex = that.data.data.total_price < that.data.data.camel_card_balance ? 0 : 1;
          var payId = that.data.data.total_price < that.data.data.camel_card_balance ? 3 : 1;//后台的id
          that.setData({ data: newdata, payIndex: payIndex, payId: payIndex, sale_box_tow_index: '' })

        } else {
          that.setData({ address_id: 0, address: null, sale_box_tow_index: '' })
        }
        var goods = that.data.data.goods;
        if (that.data.actionType == 'buy') {
          buyData(that, that.data.data.goods[0].goods_id, that.data.data.goods[0].product_id, goods[0].number, that.data.couponId)
        } else if (that.data.actionType == 'cart') {
          carData(that, that.data.cart_id, that.data.couponId);
        }
      }
    })




  },
  // 优惠劵  立减金
  discount_click: function (e) {
    var that = this;
    var sale_box = that.data.sale_box;
    var index = e.currentTarget.dataset.index;
    var discount_text = '';

    if (sale_box[2][index].checked == 1) {
      sale_box[2][index].checked = 0;
      for (var i = 0; i < sale_box[2][index].content.length; i++) {
        sale_box[2][index].content[i].checked = 0;
      }
    } else if (sale_box[2][index].checked == 0) {
      for (var i = 0; i < sale_box[2].length; i++) {
        sale_box[2][i].checked = 0;
        for (var g = 0; g < sale_box[2][i].content.length; g++) {
          sale_box[2][i].content[g].checked = 0;
        }
      }
      sale_box[2][index].checked = 1;
      sale_box[2][index].content[0].checked = 1;

    }
    if (sale_box[2][index].checked == 1) {
      discount_text = sale_box[2][index].content[0].couponName;
    }

    that.setData({
      sale_box: sale_box,
      sale_box_tow_index: index,
      discount_text: discount_text,
      "sale_box_checked[2]": [index, 0],
      couponId:0,
    })


    if (that.data.actionType == 'buy') {
      buyData(that, that.data.data.goods[0].goods_id, that.data.data.goods[0].product_id, that.data.data.goods[0].number, sale_box[2][index].content[0].couponId)
    } else if (that.data.actionType == 'cart') {
      carData(that, that.data.cart_id, sale_box[2][index].content[0].couponId);
    }


  },

  //活动优惠选择
  radioChange: function (e) {
    console.log('选择');
    var that = this;

    var value = e.currentTarget.dataset.value;
    var row_id = e.currentTarget.dataset.row_id;
    var detail_value = value.split(",");
    // var sale_box_checked = that.data.sale_box_checked;
    var copy_sale_box_num = undefined;
    var sale_box = that.data.sale_box;

    for (var i = 0; i < sale_box[row_id].length; i++) {
      if (sale_box[row_id][i].checked == 1) {
        copy_sale_box_num = i;
      }
    }


    for (var i in that.data.sale_box[2]) {
      if (that.data.sale_box[2][i].checked) {
        for (var g in that.data.sale_box[2][i].content) {
          if (that.data.sale_box[2][i].content[g].checked && that.data.sale_box_checked[2][1] == detail_value[1]) {
            detail_value[0] = '-1';
          }
        }
      }
    }

    that.setData({
      isAnimation: false,
      copy_sale_box_num: copy_sale_box_num,
      "sale_box_checked[2][1]": detail_value[1],
      couponId: detail_value[0],
    })
    if (value != undefined) {

      var goods = that.data.data.goods;
      var num = goods[0].number;

      if (that.data.actionType == 'buy') {
        buyData(that, that.data.data.goods[0].goods_id, that.data.data.goods[0].product_id, goods[0].number, that.data.couponId, detail_value[1], row_id)
      } else if (that.data.actionType == 'cart') {
        carData(that, that.data.cart_id, that.data.couponId, detail_value[1], row_id);
      }

    }

  },
  //叠加金选择
  overlay_click: function (e) {
    var that = this;

    var value = e.currentTarget.dataset.value;
    var detail_value = value.split(",");

    var sale_box = that.data.sale_box;
    var repeatId = '';
    for (var i in sale_box[1]) {
      if (i == detail_value[1]) {
        if (sale_box[1][i].checked) {
          sale_box[1][i].checked = 0;
          repeatId = '-1';
        } else {
          sale_box[1][i].checked = 1;
          repeatId = sale_box[1][i].id;
        }
      } else {
        sale_box[1][i].checked = 0;
      }
    }

    that.setData({
      repeatId: repeatId,
      sale_box: sale_box,
      isAnimation: false,
    })

    if (value != undefined) {

      var goods = that.data.data.goods;
      var num = goods[0].number;



      if (that.data.actionType == 'buy') {
        buyData(that, that.data.data.goods[0].goods_id, that.data.data.goods[0].product_id, goods[0].number, that.data.couponId)
      } else if (that.data.actionType == 'cart') {
        carData(that, that.data.cart_id, that.data.couponId);
      }

    }
  },
  //进入商品详情
  goodslink: function (e) {
    wx.redirectTo({
      url: '/pages/index/detail/index?id=' + e.currentTarget.id,
    })
  },
  // 商品数量操作
  control_btn: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var control = that.data.control;
    if (control[index] == true) {
      control[index] = false;
    } else {
      control[index] = true;
    }
    that.setData({
      control: control,
    })
  },
  confine_control_btn: function () {
    wx.showModal({
      title: '提示',
      content: '每款抽奖团商品每人仅限参团一次',
    })
  },
  // ****************************************************************************************商品增加数量
  add_num: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var goods = that.data.data.goods;
    var num = goods[index].number;

    that.setData({ sale_box_checked: [, [0], [0, 0]], couponId: 0, })
    if (parseInt(goods[index].number) < parseInt(goods[index].store_nums)) {
      goods[index].number = ++num;//修改数量
      if (that.data.actionType == 'buy') {
        buyData(that, that.data.data.goods[0].goods_id, that.data.data.goods[0].product_id, goods[index].number)
      } else if (that.data.actionType == 'cart') {
        wx.request({
          url: app.url + 'api_order/edit_cart_number',
          data: {
            'cart_id': goods[index].goods_car_id,
            number: goods[index].number,
          },
          header: {
            'content-type': 'application/json',
            'token': wx.getStorageSync('token_key')
          }, success: function (json) {
            if (!json.data.done) {
              that.setData({
                goods: goods[index].number--,
              })
              app.apperror(json);
            } else {
              carData(that, that.data.cart_id, that.data.couponId)
            }
          }
        })

      }
    } else {
      //提示信息
      wx.showToast({
        title: '已达最大库存',  //标题  
        icon: 'loading',
        duration: 1500,
      })
    }
  },
  //  ****************************************************************************************商品减去数量
  dele_num: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var goods = that.data.data.goods;
    var num = goods[index].number;
    that.setData({ sale_box_checked: [, [0], [0, 0]], couponId: 0, })
    if (num > 1) {
      goods[index].number = --num;//修改数量

      if (that.data.actionType == 'buy') {
        buyData(that, that.data.data.goods[0].goods_id, that.data.data.goods[0].product_id, goods[index].number)
      } else if (that.data.actionType == 'cart') {
        wx.request({
          url: app.url + 'api_order/edit_cart_number',
          data: {
            'cart_id': goods[index].goods_car_id,
            number: goods[index].number
          },
          header: {
            'content-type': 'application/json',
            'token': wx.getStorageSync('token_key')
          }, success: function (json) {
            if (!json.data.done) {
              app.apperror(json);
            } else {
              carData(that, that.data.cart_id, that.data.couponId)
            }
          }
        })

      }

    }
  },
  //查看优惠
  sale_btn: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;

    var sale_box = that.data.sale_box;
    var sale_box_checked = [];
    for (var one in sale_box[1]) {
      if (sale_box[1][one].checked == 1) {
        sale_box_checked[1] = one;
      }
    }
    console.log('优惠券，立减金');
    //优惠券，立减金
    sale_box_checked[2] = [];
    for (var two in sale_box[2]) {
      if (sale_box[2][two].checked == 1) {
        sale_box_checked[2].push(two);
        for (var k in sale_box[2][two].content) {
          if (sale_box[2][two].content[k].checked == 1) {
            sale_box_checked[2].push(k);
          }
        }
      }
    }


    that.setData({
      isAnimation: true,
      row_id: index,
      sale_box_checked: sale_box_checked,
    })
  },
  // 悬浮被单击
  xuanfuTAP: function () {
    var that = this;
    that.setData({
      isAnimation: false,
    })
  },
  paymethodChange: function (e) {
    this.setData({
      payIndex: e.detail.value
    })
  },
  // 添加收货人信息
  addAddressTAP: function () {
    wx.navigateTo({
      url: './addressMsg/addPersion/index?is_order=1',
    })

  },
  //选择收货地址
  /* addressListTAP: function () {
     var that = this;
     wx.chooseAddress({
       success: function (res) {
         // 添加至后台
         wx.request({
           url: app.url + 'api_user/chooseWeChatAddress',
           data: {
             accept_name: res.userName,
             province: res.provinceName,
             city: res.cityName,
             area: res.countyName,
             address: res.detailInfo,
             zip: res.postalCode,
             mobile: res.telNumber,
             pintuan: wx.getStorageSync('pintuan'),
             goods_is_huofu: that.data.data.goods[0].is_huofu,
           },
           header: {
             'content-type': 'application/json',
             'token': wx.getStorageSync('token_key')
 
           }, success: function (json) {
             if (json.data.done == true) {
               var result = json.data.result;
               var newdata = that.data.data;
               newdata.address.accept_name = result.accept_name
               newdata.address.mobile = result.mobile
               newdata.address.province_name = result.province_val
               newdata.address.city_name = result.city_val
               newdata.address.area_name = result.area_val
               newdata.address.address = result.address
               newdata.address.id = result.id;
               var payIndex = that.data.data.total_price < that.data.data.camel_card_balance ? 0 : 1;
               var payId = that.data.data.total_price < that.data.data.camel_card_balance ? 3 : 1;//后台的id
               that.setData({ data: newdata, payIndex: payIndex, payId: payIndex, 'data.is_huofu': result.is_huofu })
               
               var goods = that.data.data.goods;
               var num = goods[0].number;
               if (that.data.actionType == 'buy') {
                 buyData(that, that.data.data.goods[0].goods_id, that.data.data.goods[0].product_id, goods[0].number, that.data.couponId)
               } else if (that.data.actionType == 'cart') {
                 carData(that, that.data.cart_id, that.data.couponId);
               }
             } else {
               wx.showModal({
                 title: '提示',
                 content: json.data.message,
               })
             }
           }
         })
       }, fail: function (res) {
         wx.showModal({
           title: '温馨提醒',
           content: '需要获取您的地理位置才能使用小程序',
           cancelText: '取消',
           confirmText: '获取位置',
           success: function (res) {
             if (res.confirm) {
               getAuthor(that);
             } else if (res.cancel) {
               // getAuthor(that);
             }
           }
         })
       }
 
     })
   }, */
  addressListTAP: function (o) {
    var pagesObj = getCurrentPages()

    wx.navigateTo({
      url: '/pages/address/index/index?on_use=' + o.currentTarget.id + '&is_order=1',
    })
  },

  //请求拼团信息
  getTeamStatus: function (orderId) {
    //跳转到邀请页
    wx.request({
      url: app.url + "api_team/getTeamStatus",
      data: {
        id: orderId
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },
      success: function (orderInfo) {
        if (orderInfo.data.result.team_status == '1') {
          wx.redirectTo({
            url: '/pages/mygroup/invite/invite?orderId=' + orderId,
          })
        } else {
          wx.redirectTo({
            url: '/pages/mygroup/mygroupdetail/mygroupdetail?order_id=' + orderId,
          })
        }
      }
    })
  }

})


//购物车数据 

/*********  购物车id***********/
function carData(that, car_id, couponId, index, row_id) {

  wx.request({
    url: app.url + 'api_order/orderDisplayV1',
    data: {
      cart_id: car_id,
      address_id: that.data.address_id,
      couponId: (!couponId || couponId == 'undefined' ? '0' : couponId),
      repeatId: (!that.data.repeatId || that.data.repeatId == 'undefined' ? '0' : that.data.repeatId),
    },
    header: {
      'content-type': 'application/json',
      'token': wx.getStorageSync('token_key')
    }, success: function (json) {
      if (json.data.done) {

        var goodsinfo = {
          cart_id: car_id,
          actionType: 'cart',
        }
        //在添加地址返回取这里存的id。
        wx.setStorageSync('goodsinfo', goodsinfo)
        var goodsinfo = wx.getStorageSync('goodsinfo')
        if (json.data.result.address) {
          that.setData({ address_id: json.data.result.address.id })
        }
        if (json.data.done) {
          json.data.result.market_price = 0;//已优惠的价格（为用户节省）
          for (var i = 0; i < json.data.result.goods.length; i++) {
            json.data.result.market_price += (json.data.result.goods[i].market_price - json.data.result.goods[i].price) * json.data.result.goods[i].number;
          }
          var sale_box = {};
          sale_box[0] = [];//活动优惠
          sale_box[1] = [];//叠加金
          sale_box[2] = [];//优惠劵  立减金

          if (typeof json.data.result.text == 'object' && json.data.result.text != null) {
            for (var i = 0; i < json.data.result.text.length; i++) {
              sale_box[0].push({ desc: json.data.result.text[i], });
            }
          }


          if (json.data.result.repeatList) {
            for (var i in json.data.result.repeatList) {
              if (i == 0 && that.data.repeatId != '-1') {
                json.data.result.repeatList[i].checked = 1;
                that.setData({ repeatId: json.data.result.repeatList[i].id })
              } else {
                json.data.result.repeatList[i].checked = 0;
              }
              sale_box[1].push(json.data.result.repeatList[i]);
            }
          }

          // 叠加金 模拟加载-------------------------------
          // sale_box[1] = [{ coupon: 30, desc: '叠加金01', checked: 1 }, { coupon: 30, desc: '叠加金02', checked: 0 }, { coupon: 40, desc: '叠加金03', checked: 0 },];
          // 优惠劵  立减金  模拟加载-------------------------------
          //写入优惠券
          for (var i in json.data.result.otherCoupon) {
            if (i == 0) {
              json.data.result.otherCoupon[i].checked = 1;
            } else {
              json.data.result.otherCoupon[i].checked = 0;
            }
          }
          var discount_box = [];
          if (json.data.result.otherCoupon != '') {
            var otherCoupon = json.data.result.otherCoupon;
            for (var i in otherCoupon) {
              if (i == 0) {
                otherCoupon[i].checked = 1;
              } else {
                otherCoupon[i].checked = 0;
              }
            }
            sale_box[2][0] = { text: '优惠券', checked: 1, content: otherCoupon, };
          } else {
            var benifitPlan = json.data.result.benifitPlan;
            sale_box[2][0] = { text: '优惠券', checked: 0, content: [], };
            sale_box[2][1] = { text: '立减金', checked: 0, content: [], };

            for (var i in benifitPlan) {
              if (benifitPlan[i].type == 0) {//分辨优惠劵
                sale_box[2][0].content.push(benifitPlan[i]);
              } else if (benifitPlan[i].type == 1) {//分辨立减金
                sale_box[2][1].content.push(benifitPlan[i]);
              }
            }

            if (sale_box[2][0].content[0] != undefined) {
              sale_box[2][0].checked = 1;
              if (that.data.couponId != '-1') {
                sale_box[2][0].content[0].checked = 1;
              } else {
                sale_box[2][0].content[0].checked = 0;
              }
            } else if (sale_box[2][1].content[0] != undefined) {
              sale_box[2][1].checked = 1;
              if (that.data.couponId != '-1') {
                sale_box[2][1].content[0].checked = 1;
              } else {
                sale_box[2][1].content[0].checked = 0;
              }
            }
          }
          //优惠劵测试------------------------------------------------------------------------------------------------



          var sale_box_checked = that.data.sale_box_checked;
          if (sale_box != '' && index != undefined) {

            if (sale_box_checked[1] != undefined && sale_box[1] != '') {
              sale_box[1][sale_box_checked[1]].checked = 1;
            }
            if (sale_box_checked[2][1] != undefined) {
              sale_box[2][sale_box_checked[2][0]].content[sale_box_checked[2][1]].checked = 1;
            }


            if (row_id == 1) {//叠加金选择判断
              for (var i in sale_box[row_id]) {
                sale_box[row_id][i].checked = 0;
              }
                sale_box[row_id][index].checked = 1;
            }
            if (row_id == 2) {//优惠劵  立减金  选择判断
              console.log('进入  优惠劵  立减金  选择判断----------------------------------------');
              var sale_box_tow_index = that.data.sale_box_tow_index;
              for (var i in sale_box[row_id]) {
                sale_box[row_id][i].checked = 0;
              }
              sale_box[row_id][sale_box_checked[2][0]].checked = 1;

              for (var h in sale_box[row_id][sale_box_checked[2][0]].content) {
                sale_box[row_id][sale_box_checked[2][0]].content[h].checked = 0;
              }

              if (that.data.couponId == '-1') {
                sale_box[row_id][sale_box_checked[2][0]].content[index].checked = 0;
                sale_box_checked[2][1] = '';
              } else {
                sale_box[row_id][sale_box_checked[2][0]].content[index].checked = 1;
                sale_box_checked[2][1] = index;
              }

            }
          }

          if (that.data.sale_box_tow_index != '' && that.data.sale_box_tow_index != undefined) {
            for (var i in sale_box[2]) {
              if (i == sale_box_checked[2][0]) {
                sale_box[2][i].checked = 1;
                for (var g in sale_box[2][i].content) {
                  if (g == sale_box_checked[2][1]) {
                    sale_box[2][i].content[g].checked = 1;
                  } else {
                    sale_box[2][i].content[g].checked = 0;
                  }
                }
              } else {
                sale_box[2][i].checked = 0;
                for (var g in sale_box[2][i].content) {
                  sale_box[2][i].content[g].checked = 0;
                }
              }
            }
          }

          //优惠劵  立减金  文字显示
          var discount_text = '';
          var couponId = '-1';
          for (var i in sale_box[2]) {
            if (sale_box[2][i].checked == 1) {
              for (var g in sale_box[2][i].content) {
                if (sale_box[2][i].content[g].checked == 1) {
                  couponId = sale_box[2][i].content[g].couponId;
                  discount_text = sale_box[2][i].content[g].couponName;
                }
              }
            }
          }

          sale_box[0].push(json.data.result.order_freight);
          var payIndex = json.data.result.total_price < json.data.result.camel_card_balance ? 0 : 1;
          var payId = json.data.result.total_price < json.data.result.camel_card_balance ? 3 : 1;//后台的id
          that.setData({ 
            data: json.data.result, 
            payIndex: payIndex, 
            payId: payId, 
            actionType: 'cart', 
            cart_id: car_id, 
            sale_box: sale_box, 
            discount_text: discount_text, 
            sale_box_checked: sale_box_checked, 
            couponId: couponId, });
          if (json.data.result.address.length == 0) {
            wx.navigateTo({
              url: '/pages/index/detail/orderDetail/addressMsg/addPersion/index',
            })
          }
        } else {
          that.setData({
            'cart_id': car_id,
            'actionType': 'cart'
          })
        }
      } else {
        that.setData({
          goods: goods[index].number--,
        })
        app.apperror(json);
      }
    }

  })

}



function buyData(that, goods_id, product_id, number, couponId, index, row_id) {

  wx.request({
    url: app.url + 'api_order/orderDisplay',
    data: {
      goods_id: goods_id,
      product_id: product_id,
      number: number,
      pintuan: wx.getStorageSync('pintuan'),
      regiment_id: (that.data.regiment_id != 0 || that.data.regiment_id != undefined) ? that.data.regiment_id : 0,
      isOrderPage: 1,
      address_id: that.data.address_id,
      couponId: (!couponId || couponId == 'undefined' ? '0' : couponId),
      repeatId: (!that.data.repeatId || that.data.repeatId == 'undefined' ? '0' : that.data.repeatId),
    },
    header: {
      'content-type': 'application/json',
      'token': wx.getStorageSync('token_key')
    }, success: function (json) {
      var goodsinfo = {
        goods_id: goods_id,
        product_id: product_id,
        number: number,
        actionType: 'buy',
      }
      //在添加地址返回取这里存的id。
      wx.setStorageSync('goodsinfo', goodsinfo)
      var goodsinfo = wx.getStorageSync('goodsinfo');

      if (json.data.done) {
        //如果是团长免单团，那么这里的价格显示为0.00
        if (json.data.result.goods[0].action_type == '5' && !that.data.tSign) {
          json.data.result.total_price = '0.00';
          json.data.result.goods[0].price = '0.00';
        }

        var sale_box = {};
        sale_box[0] = [];//活动优惠
        sale_box[1] = [];//叠加金
        sale_box[2] = [];//优惠劵  立减金

        if (typeof json.data.result.text == 'object' && json.data.result.text != null) {
          for (var x in json.data.result.text) {
            sale_box[0].push({ desc: json.data.result.text[x], });
          }
        }

        if (json.data.result.repeatList) {
          for (var i in json.data.result.repeatList) {
            if (i == 0 && that.data.repeatId != '-1') {
              json.data.result.repeatList[i].checked = 1;
              that.setData({ repeatId: json.data.result.repeatList[i].id })
            } else {
              json.data.result.repeatList[i].checked = 0;
            }
            sale_box[1].push(json.data.result.repeatList[i]);
          }
        }


        //写入优惠券
        for (var i in json.data.result.otherCoupon) {
          if (i == 0) {
            json.data.result.otherCoupon[i].checked = 1;
          } else {
            json.data.result.otherCoupon[i].checked = 0;
          }
        }
        var discount_box = [];

        if (json.data.result.otherCoupon != undefined) {
          var otherCoupon = json.data.result.otherCoupon;
          for (var i in otherCoupon) {
            if (i == 0) {
              otherCoupon[i].checked = 1;
            } else {
              otherCoupon[i].checked = 0;
            }
          }
          sale_box[2][0] = { text: '优惠券', checked: 1, content: otherCoupon, };
        } else {
          var benifitPlan = json.data.result.benifitPlan;

          sale_box[2][0] = { text: '优惠券', checked: 0, content: [], };
          sale_box[2][1] = { text: '立减金', checked: 0, content: [], };

          for (var i in benifitPlan) {
            if (benifitPlan[i].type == 0) {//分辨优惠劵
              sale_box[2][0].content.push(benifitPlan[i]);
            } else if (benifitPlan[i].type == 1) {//分辨立减金
              sale_box[2][1].content.push(benifitPlan[i]);
            }
          }

          if (sale_box[2][0].content[0] != undefined) {
            sale_box[2][0].checked = 1;
            if (that.data.couponId != '-1') {
              sale_box[2][0].content[0].checked = 1;
            }else{
              sale_box[2][0].content[0].checked = 0;
            }
          } else if (sale_box[2][1].content[0] != undefined) {
            sale_box[2][1].checked = 1;
            if (that.data.couponId != '-1') {
              sale_box[2][1].content[0].checked = 1;
            } else {
              sale_box[2][1].content[0].checked = 0;
            }
          }

        }

        //写入立减金


        //优惠劵测试------------------------------------------------------------------------------------------------


        var sale_box_checked = that.data.sale_box_checked;

        if (sale_box != '' && index != undefined) {
          if (sale_box_checked[1] != undefined && sale_box[1] != '') {
            sale_box[1][sale_box_checked[1]].checked = 1;
          }
          if (sale_box_checked[2][1] != undefined) {
            sale_box[2][sale_box_checked[2][0]].content[sale_box_checked[2][1]].checked = 1;
          }




          //叠加金选择判断
          if (row_id == 1) {
            for (var i in sale_box[row_id]) {
              sale_box[row_id][i].checked = 0;
            }
            sale_box[row_id][index].checked = 1;
          }
          //优惠劵  立减金  选择判断
          if (row_id == 2) {
            console.log('进入  优惠劵  立减金  选择判断----------------------------------------');
            var sale_box_tow_index = that.data.sale_box_tow_index;
            for (var i in sale_box[row_id]) {
              sale_box[row_id][i].checked = 0;
            }
            sale_box[row_id][sale_box_checked[2][0]].checked = 1;

            for (var h in sale_box[row_id][sale_box_checked[2][0]].content) {
              sale_box[row_id][sale_box_checked[2][0]].content[h].checked = 0;
            }
            console.log(that.data.couponId);
            if (that.data.couponId == '-1') {
              sale_box[row_id][sale_box_checked[2][0]].content[sale_box_checked[2][1]].checked = 0;
              sale_box_checked[2][1] = '';
            } else {
              sale_box[row_id][sale_box_checked[2][0]].content[sale_box_checked[2][1]].checked = 1;
              sale_box_checked[2][1] = index;
            }
          }
        }
        console.log(sale_box[2]);

        if (that.data.sale_box_tow_index != '' && that.data.sale_box_tow_index != undefined) {
          for (var i in sale_box[2]) {
            if (i == sale_box_checked[2][0]) {
              sale_box[2][i].checked = 1;
              for (var g in sale_box[2][i].content) {
                if (g == sale_box_checked[2][1]) {
                  sale_box[2][i].content[g].checked = 1;
                } else {
                  sale_box[2][i].content[g].checked = 0;
                }
              }
            } else {
              sale_box[2][i].checked = 0;
              for (var g in sale_box[2][i].content) {
                sale_box[2][i].content[g].checked = 0;
              }
            }
          }
        }

        //优惠劵  立减金  文字显示
        var discount_text = '';
        var couponId = '-1';
        for (var i in sale_box[2]) {
          if (sale_box[2][i].checked == 1) {
            for (var g in sale_box[2][i].content) {
              if (sale_box[2][i].content[g].checked == 1) {
                couponId = sale_box[2][i].content[g].couponId;
                discount_text = sale_box[2][i].content[g].couponName;
              }
            }
          }
        }


        sale_box[0].push(json.data.result.order_freight);

        var payIndex = json.data.result.total_price < json.data.result.camel_card_balance ? 0 : 1;
        var payId = json.data.result.total_price < json.data.result.camel_card_balance ? 3 : 1;//后台的id

        that.setData({ 
          data: json.data.result, 
          payIndex: payIndex, 
          payId: payId, 
          actionType: 'buy', 
          sale_box: sale_box, 
          discount_text: discount_text, 
          sale_box_checked: sale_box_checked, 
          couponId: couponId, 
          address_id: json.data.result.address.id,
        });
        if (json.data.result.address.length == 0) {
          wx.navigateTo({
            url: '/pages/index/detail/orderDetail/addressMsg/addPersion/index',
          })
        }
      } else {
        that.setData({
          'data.goods[0].number': --number,
        })
        app.apperror(json);
      }
    }
  })
}


//强制授权地理位置
function getAuthor(that) {
  wx.getSetting({
    success(res) {
      if (!res.authSetting['scope.userLocation']) {
        wx.openSetting({
          success: (res) => {

          }
        })
      }
    }
  })
}

//通过选择返回支付id
function getPayId(select_id) {
  var payId = 1
  switch (select_id) {
    case 0:
      payId = 3;
      break;
    case 1:
      payId = 1;
      break;
    case 2:
      payId = 0;
      break;
  }
  return payId;
}